$(function(){
	//获取小区选择值
	checkImage();
	checkLogin();
	getDefaultPoi();
	chooseDistrict();
	submitTest();
	//确认发布按钮
	$('.admin-post').click(function(){
		if(!$(this).hasClass('disabled')){
			searilize();
		}
	})
	//选择小区跳转
	$('.choose-district').click(function(){
		location.href='../choose-district.html';
	})
	//增加单选选项
	$('.addradio-wrapper button').click(function(){
		if(!$(this).hasClass('disabled')){
			var radioTitle = $('.radio-title').val();
			var radioList = $('.addradio-wrapper .radio-item');
			var radioVal = [];
			var html = '<div class="item-box radioBox"><span class="item-title">'+radioTitle+'：</span>'
			for(var i = 0,l = radioList.length;i<l;i++){
				html += '<input type="radio"><label>'+radioList[i].value+'</label>';
			}
			html += '<button class="item-delete">删除</button></div>';
			$('.admin-post').before($(html));
			$('.addradio-wrapper input').val('');
			$('.addradio-wrapper input:gt(2)').remove();
			$(this).addClass('disabled');
		}
	})
	//增加选项确定按钮验证
	$('.addradio-wrapper').on('input propertychange','input',function(){
		checkEmpty($('.addradio-wrapper'),$('.addradio-wrapper button'));
	});
	$('.addtext-wrapper').on('input propertychange','input',function(){
		checkEmpty($('.addtext-wrapper'),$('.addtext-wrapper button'));
	});
	$('.post-sign').on('input propertychange','input,textarea',function(){
		submitTest();
	});
	//增加单选
	$('.add-radio').click(function(){
		$('.addradio-wrapper input').val('');
		$('.addradio-wrapper input:gt(2)').remove();
		$('.addradio-wrapper').stop().slideToggle();
		$('.addradio-wrapper button').addClass('disabled');
	})
	$('.addradio-wrapper .add-link').click(function(){
		var $obtionBox = $('.radio-item');
		var index = $obtionBox.length;
		if(index>20){
			alert('选项超过最大数量！');
			return false;
		}
		var zhNum =  ["一","二","三","四","五","六","七","八","九",'十','十一','十二','十三','十四','十五','十六','十七','十八','十九','二十'];
		var optionBox = $('<input class="radio-item" placeholder="选项'+zhNum[index]+'" style="display:none">');
		$('.add-link').before(optionBox);
		optionBox.slideDown();
		$('.addradio-wrapper button').addClass('disabled');
		//$('.admin-post').addClass('disable');
	})
	//增加文本选项
	$('.add-text').click(function(){
		$('.addtext-wrapper').val('').stop().slideToggle();
	});
	$('.addtext-wrapper button').on('click',function(){
		var textTitle =  $('.addtext-wrapper input').val();
		if(!$(this).hasClass('disabled')){
			$('.addtext-wrapper input').val('');
			var html = '<div class="item-box"><span class="item-title">'+textTitle+'：</span><span class="bottom-line"></span><button class="item-delete">删除</button></div>';
			$('.admin-post').before($(html));
			$(this).addClass('disabled');
		}
	})
	$(document).on('click','.item-delete',function(){
		var that = $(this).parent();
		that.remove();
	})
	//上传图片配置
	var domain_name = (env == 'pre' || env == 'sit') ? 'cnsuning.com' : 'suning.com';
    document.domain = window.domain = domain_name;
	$('#filechooser').AjaxFileUpload({
        action:  baseurl+'/post/save/fileUpload.do',
        onComplete: uploadCallback
    })
	//starMobiscroll配置
	var starMobiscroll = $('#start-time').mobiscroll().date({
		lang:"zh",
		setText:'确定',
		cancelText:'取消',
		dayText:'日',
		monthText:'月',
		yearText:'年',
		dateFormat: 'yy-mm-dd',// 日期格式
		endYear:2050,
		min: new Date(),
		onCancel: function (event, inst) {
			//取消输入，清空input，并禁用结束时间选择
			$('#start-time,#over-time').val('');
			$('#start-time').attr('placeholder','起始时间');
     		$('#over-time').mobiscroll('option',{
				disabled:true
			});
			$('.admin-post').addClass('disabled');
			localStorage.removeItem('startDate');
			localStorage.removeItem('overDate');
		},
		onSet: function (event, inst) {
			//选定开始时间
			var startDate = $('#start-time').mobiscroll('getVal');
			var overDate =$('#over-time').mobiscroll('getVal');
			submitTest();
			if(overDate<startDate){
				//判断开始时间不得大于结束时间
				$('#over-time').val('');
				$('.admin-post').addClass('disabled');
			}
			//修改结束时间参数
			$('#over-time').mobiscroll('option',{
				min: startDate,
				disabled:false
			});
			//console.log(startDate);
			localStorage.setItem('startDate',startDate);
		}
	});
	var overMobiscroll = $('#over-time').mobiscroll().date({
		lang:"zh",
		setText:'确定',
		cancelText:'取消',
		dayText:'日',
		monthText:'月',
		yearText:'年',
		dateFormat: 'yy-mm-dd',// 日期格式
		endYear:2050,
		disabled:true,
		onCancel:function (event, inst) {
    		$('#over-time').val('');
    		$('.admin-post').addClass('disabled');
    		localStorage.removeItem('overDate');
    	},
		onSet:function(event, inst){
			var overDate =$('#over-time').mobiscroll('getVal');
			submitTest();
			localStorage.overDate = overDate;
			console.log(localStorage.overDate);
		}
	});
	checkDate();
})
//检查时间设置
var checkDate =function(){
	if(localStorage.overDate){
		var date = new Date(localStorage.overDate);
		var dateStr = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
		$('#over-time').val(dateStr);
	}
	if(localStorage.startDate){
		var date = new Date(localStorage.startDate);
		var dateStr = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
		$('#start-time').val(dateStr);
		$('#over-time').mobiscroll('option',{
			min: date,
			disabled:false
		});
	}
}
//上传图片函数

var checkImage = function () {
	if(localStorage.imgUpload){
    	var imgArry = localStorage.imgUpload.split(',');
    	for(var i = 0,l=imgArry.length;i<l;i++){
    		var ele = $('<li class="uploadfuck"><img></li>');
		    ele.find('img').attr('src', imgArry[i]).show();
		    $('.sendimg').find('ul').append(ele);
    	}
    	if ($('.uploadfuck').length == 5) {
	        $('.sendimg').find('a').hide();
	    }
    }
    var all = true
    var imgs = $('img');
    for (var i = 0; i < imgs.length; i++) {
        if (!$(imgs[i]).attr('src')) {
            $(imgs[i]).hide();
            all = false;
        }
    }
    if (all) {
        $('.upload-text').hide();
    }
    else {
        $('.upload-text').show();
    }

}
function uploadCallback(data) {
	if(data.result==0){
		var ele = $('<li class="uploadfuck"><img></li>');
	    ele.find('img').attr('src', data.url).show();
	    $('.sendimg').find('ul').append(ele);
	    if ($('.uploadfuck').length == 5) {
	        $('.sendimg').find('a').hide();
	    }

	    var imgs = $('.uploadfuck').find('img').map(function(v,i){return i.src}).toArray().toString();
	    localStorage.setItem('imgUpload',imgs);
	}else{
        console.log(data.errorMsg)
	}
}
//验证绑定
var checkEmpty=function($addWrapper,$button){
	var disabled =false;
	var domList = $addWrapper.find('input');
	for(var i=0,l=domList.length;i<l;i++){
		if($.trim(domList[i].value)==''){
			disabled = true;
			break;
		}
	}
	if(!disabled){
		$button.removeClass('disabled');
	}else{
		$button.addClass('disabled');
	}
}
var submitTest =function(){
	var disabled =false;
	var domList = $('.post-sign').children('input').add('textarea');
	for(var i=0,l=domList.length;i<l;i++){
		if($.trim(domList[i].value)==''){
			disabled = true;
			break;
		}
	}
	if(!disabled){
		$('.admin-post').removeClass('disabled');
	}else{
		$('.admin-post').addClass('disabled');
	}
}
//获取默认小区
var getDefaultPoi = function(){
	Prepare({
        complete: function (location) {
        	console.log(location);
        	var poiId =  location.poiId;
        	var poiName = location.poiName;
        	$('.choose-district span').html('（'+poiName+'）');
        	$('.choose-district span').attr('poiId',poiId);
        }
    })
}
//检测选择小区
var chooseDistrict = function(){
	var district = localStorage.district;
	if(district){
		$('.choose-district span').html('（'+district+'）');
		$('.choose-district span').attr('poiId',localStorage.poiId);
	}
}
var searilize = function(){
	checkLogin(function () {
		var postTitle = $('#post-title').val();
		var postContent =$('.admin-textarea').val();
		var poiId = $('.choose-district span').attr('poiId');
		var startTime = $('#start-time').val();
		var endTime = $('#over-time').val();
		var address = $('#address').val();
		var userCount = $('#number').val();
		//var Images = localStorage.imgUpload?localStorage.imgUpload:'';//???
		var formArray = [];//表单信息转化数组
		var $itemBox = $('.item-box');
		for(var i=0,l=$itemBox.length;i<l;i++){
			var obj = {};
			obj.listOrder = i;
			if($($itemBox[i]).hasClass('radioBox')){
				obj.itemType = 1;
				var itemOptionValue=$($itemBox[i]).find('label').map(function(v,i){return i.innerHTML}).toArray().toString();
				obj.itemOptionValue =itemOptionValue;
				console.log(itemOptionValue);
			}else{
				obj.itemType = 0;
			}
			obj.itemIdentify = guid();
			obj.itemName = $($itemBox[i]).find('.item-title').html();
			obj.itemTip = $($itemBox[i]).find('.item-title').html();
			formArray.push(obj);
		}
		signFormList = JSON.stringify(formArray);
		console.log(signFormList);

		// console.log(poiId);
		console.log(signFormList);
		var images = localStorage.getItem('imgUpload')?localStorage.getItem('imgUpload'):'';
		console.log(images);
		$.ajax({
			url:baseurl+'/post/publish/sign.do',
			type:'GET',
			dataType:'jsonp',
			data:{
				postTitle:postTitle,
				postContent:postContent,
				images:images,
				poiId:poiId,
				startTime:startTime+' 00:00:00',
				endTime:endTime+' 00:00:00',
				address:address,
				userCount:userCount,
				signFormList:signFormList
			}
		}).then(function(data){
			if(data.resultCode==0){
				console.log('发布成功');
				AlertBox({
                    msg: '发布成功',
                    type: 'mini',
                })
				localStorage.removeItem('imgUpload');
				localStorage.removeItem('overDate');
				localStorage.removeItem('startDate');
				localStorage.removeItem('district');
				localStorage.removeItem('poiId');
				setTimeout(function(){
					location.href="/duimen/index.html?start='xiaoqu'"
				})
			} else {
				console.log(data.resultMsg);
			}
		})

	})
	
	
}
// Generate four random hex digits.
function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
// Generate a pseudo-GUID by concatenating random hexadecimal.
function guid() {
   return (S4()+S4());
};

